
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>canvas</title>
<style>
#tutorial{
border: 1px solid
}
</style>
</head>
<body>
<canvas id="tutorial" width="450" height="450"></canvas>
<div>
	<button onclick="clearCanvas()">清空</button>
	<button onclick="saveCanvas()">保存</button>
	<button onclick="saveAsFile()">图片转文件</button>
</div>
</body>
<script type="text/javascript">
//let events = ["mousedown","mousemove","mouseup"];
let canvas = null;
let ctx;
window.onload = function(){
canvas = document.getElementById("tutorial");
if(canvas){
ctx = canvas.getContext("2d");
//设置画笔属性
    ctx.lineWidth = 5;
    ctx.lineCap = 'round';//线段两端圆滑
    ctx.lineJoin = 'round';//两条线条相交时，创建圆形边角
    ctx.strokeStyle = "#000";//线条颜色
    ctx.shadowBlur = 1;//阴影的模糊级数
    ctx.shadowColor = "#000";//阴影的颜色
//canvas元素添加鼠标按下时的监听事件
    canvas.addEventListener("mousedown",startHandler);
}else{
//alert(“您的浏览器不支持canvas标签，请升级或更换浏览器”);
}
}
 
function startHandler(){
//开始一条新路径，这一步很重要否则所有的点都会连线
ctx.beginPath();
//鼠标按下时就定义另外两个监听事件
canvas.addEventListener("mousemove",moveHandler);
 
document.body.addEventListener("mouseup",endHandler);
}
 
function moveHandler(e){
let position = canvas.getBoundingClientRect();//获取canvas的大小及其相对于视口的位置
let x = e.clientX - position.left;//这样才能获得触发点在canvas画布上的坐标
let y = e.clientY - position.top;
ctx.lineTo(x,y);//如果当前只有一个点，lineTo也会绘制出一个点
ctx.stroke();//描边
}
 
function endHandler(){
//移除另外两个事件监听
document.body.removeEventListener("mouseup",endHandler);
canvas.removeEventListener("mousemove",moveHandler);
}
</script>
</html>